#!/bin/bash
# EMS Dispatch Service - systemd 单元文件生成脚本
# 用于在树莓派上设置开机自启

set -e

PROJECT_ROOT="/home/sunfly/ems-cpp-v1"
UNIT_FILE="/etc/systemd/system/ems-dispatch.service"

echo "========================================="
echo "  EMS Dispatch 开机自启配置工具"
echo "========================================="
echo

# 检查是否以 root 运行
if [ "$EUID" -ne 0 ]; then
    echo "错误: 请使用 sudo 运行此脚本"
    echo "示例: sudo ./setup-systemd.sh"
    exit 1
fi

# 自动检测运行用户
echo "正在检测运行用户..."
if id pi &>/dev/null; then
    RUN_USER="pi"
    RUN_GROUP="pi"
    echo "✓ 使用用户: pi"
elif id sunfly &>/dev/null; then
    RUN_USER="sunfly"
    RUN_GROUP="sunfly"
    echo "✓ 使用用户: sunfly"
else
    # 使用项目目录的所有者
    RUN_USER=$(stat -c '%U' "$PROJECT_ROOT" 2>/dev/null || stat -f '%Su' "$PROJECT_ROOT" 2>/dev/null)
    RUN_GROUP=$(stat -c '%G' "$PROJECT_ROOT" 2>/dev/null || stat -f '%Sg' "$PROJECT_ROOT" 2>/dev/null)
    echo "✓ 使用目录所有者: $RUN_USER:$RUN_GROUP"
fi

# 验证用户存在
if ! id "$RUN_USER" &>/dev/null; then
    echo "错误: 用户 $RUN_USER 不存在"
    echo "当前系统用户列表:"
    cut -d: -f1 /etc/passwd | grep -v "^_" | head -20
    exit 1
fi

echo "  用户: $RUN_USER"
echo "  组: $RUN_GROUP"
echo

# 检查项目目录
if [ ! -d "$PROJECT_ROOT" ]; then
    echo "错误: 项目目录不存在: $PROJECT_ROOT"
    echo "请修改脚本中的 PROJECT_ROOT 变量"
    exit 1
fi

# 检查可执行文件
EXECUTABLE="$PROJECT_ROOT/build/bin/ems-cpp-v1"
if [ ! -f "$EXECUTABLE" ]; then
    echo "错误: 可执行文件不存在: $EXECUTABLE"
    echo "请先编译项目:"
    echo "  cd $PROJECT_ROOT"
    echo "  mkdir -p build && cd build"
    echo "  cmake .. && cmake --build . -- -j4"
    exit 1
fi

# 确保可执行权限
chmod +x "$EXECUTABLE"
echo "✓ 可执行文件: $EXECUTABLE"

# 检查配置文件目录
CONFIG_DIR="$PROJECT_ROOT/config"
if [ ! -d "$CONFIG_DIR" ]; then
    echo "警告: 配置目录不存在: $CONFIG_DIR"
fi

# 写入 systemd 单元文件
echo
echo "正在创建 systemd 单元文件: $UNIT_FILE"
cat > "$UNIT_FILE" <<EOF
[Unit]
Description=EMS Energy Management System
After=network-online.target
Wants=network-online.target

[Service]
Type=simple
User=$RUN_USER
Group=$RUN_GROUP
WorkingDirectory=$PROJECT_ROOT
ExecStart=$EXECUTABLE --config $CONFIG_DIR
Restart=always
RestartSec=5
StartLimitBurst=5
StartLimitIntervalSec=60
StandardOutput=journal
StandardError=journal
SyslogIdentifier=ems-dispatch

[Install]
WantedBy=multi-user.target
EOF

echo "✓ 单元文件已创建"

# 重新加载 systemd
echo
echo "正在重新加载 systemd 配置..."
systemctl daemon-reload
echo "✓ systemd 配置已重新加载"

# 启用服务
echo
echo "正在启用开机自启..."
systemctl enable ems-dispatch.service
echo "✓ 开机自启已启用"

# 显示服务状态
echo
echo "========================================="
echo "  配置完成!"
echo "========================================="
echo
echo "常用命令:"
echo "  启动服务:   sudo systemctl start ems-dispatch.service"
echo "  停止服务:   sudo systemctl stop ems-dispatch.service"
echo "  重启服务:   sudo systemctl restart ems-dispatch.service"
echo "  查看状态:   sudo systemctl status ems-dispatch.service"
echo "  查看日志:   sudo journalctl -u ems-dispatch.service -f"
echo "  禁用自启:   sudo systemctl disable ems-dispatch.service"
echo
echo "是否立即启动服务? (y/n)"
read -r response
if [[ "$response" =~ ^([yY][eE][sS]|[yY])$ ]]; then
    systemctl start ems-dispatch.service
    echo
    echo "✓ 服务已启动"
    echo
    systemctl status ems-dispatch.service --no-pager
else
    echo
    echo "跳过启动。稍后可用以下命令手动启动:"
    echo "  sudo systemctl start ems-dispatch.service"
fi

echo
echo "完成! 重启树莓派后服务将自动启动。"
